package cn.tedu.note.service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.tedu.note.dao.UserDao;
import cn.tedu.note.entity.User;
import cn.tedu.note.util.Util;

@Service("userService")
public class UserServiceImpl 
	implements UserService{
	
	@Resource
	private UserDao userDao;
	
	@Transactional
	public User login(String name, 
			String password) 
		throws NameException ,
		PasswordException {
		
		System.out.println("Login");
		
		//String s=null;
		//s.charAt(0);
		
		if(name==null || name.trim().isEmpty()){
			throw new NameException("不能空");
		}
		if(password==null ||
			password.trim().isEmpty()){
			throw new PasswordException("不能空");
		}
		//根据用户名查找用户信息
		//在检查密码是否正确
		User user=userDao
			.findUserByName(name);
		if(user==null){
			throw new NameException("错误");
		}
		//password 密码的明文
		String md5=Util.saltMd5(password);
		//比较摘要,如果摘要一样则明文(密码)一样
		System.out.println(md5); 
		if(user.getPassword().equals(md5)){
			String token=
				UUID.randomUUID().toString();
			user.setToken(token);
			Map<String, Object> userInfo=
				new HashMap<String, Object>();
			userInfo.put("id", user.getId());
			userInfo.put("token", token);
			userDao.updateUser(userInfo);
			return user;
		}
		throw new PasswordException("错误");
	};
	
	@Transactional
	public User regist(String name, 
			String nick, 
			String password, 
			String confirm)
			throws NameException, 
			PasswordException {
		if(name==null||name.trim().isEmpty()){
			throw new NameException("不能空");
		}
		if(password==null||
				password.trim().isEmpty()){
			throw new PasswordException("不能空");
		}
		if(! password.equals(confirm)){
			throw new PasswordException("确认不一致");
		}
		User user=userDao.findUserByName(name);
		if(user!=null){
			throw new NameException("已注册");
		}
		if(nick==null||nick.trim().isEmpty()){
			nick = name;
		}
		String id=UUID.randomUUID().toString();
		String token="";
		password = Util.saltMd5(password);
		user = new User(
			id, name, password, token, nick);
		
		userDao.addUser(user);
		
		return user;
	}
	
	/**
	 * 检查token与数据库中的token是否一致
	 */
	@Transactional(readOnly=true)
	public boolean checkToken(
			String userId, String token) {
		User user=userDao.findUserById(userId);
		return token.equals(user.getToken());
	}
	
}




